package model

import (
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"go-gin-api/app/config"
	"time"
)

var Db *DB
type DB struct {
	Hander *gorm.DB
	cfg
}
type cfg struct {
	host   string
	port   string
	user   string
	pass   string
	dbname string
	prefix string
}

//连接mysql
func Connect() (Dbase *DB) {
	//创建连接
	Dbase = Singleton()
	if err := Dbase.Open(); err != nil {
		panic(err.Error())
	}
	return
}

//创建单例模式
func Singleton() *DB {
	var dbconfig cfg
	dbconfig = cfg{
		config.DbHost,
		config.DbPort,
		config.DbUser,
		config.DbPass,
		config.DbName,
		config.DbPrefix,
	}
	return &DB{
		cfg: dbconfig,
	}
}

//mysql 连接
func (db *DB) Open() error {
	connect := fmt.Sprintf("%s:%s@(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local",
		db.user, db.pass, db.host, db.port, db.dbname)
	obj, err := gorm.Open("mysql", connect)
	if err != nil {
		return err
	}
	//转换名称时不加s
	obj.SingularTable(true)
	//打印详细日志 //TODO 调试完成后需删除
	obj.LogMode(config.DbLogMode)
	//设置连接池
	obj.DB().SetConnMaxLifetime(time.Second * time.Duration(config.DbConnMaxLifetime))
	obj.DB().SetMaxIdleConns(config.DbMaxIdleConns)
	obj.DB().SetMaxOpenConns(config.DbMaxOpenConns)
	db.Hander = obj
	return nil
}

//mysql 关闭连接
func (db *DB) Close() {
	if db != nil && db.Hander != nil {
		db.Hander.Close()
	}
}
